package com.fitso.model.context;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * Startup class for application context. This gets called at JVM startup and
 * wires up all of the beans so they are ready to go when called.
 * 
 * @author timothystorm
 */
@Service("ContextFactory")
public class ContextFactory implements ApplicationContextAware {
	private static ApplicationContext CONTEXT;

	private static final Logger logger = Logger.getLogger(ContextFactory.class);

	public static ApplicationContext getApplicationContext() {
		return CONTEXT;
	}

	/**
	 * Quick method for getting a bean out of the context. Just pass in the
	 * Interface class and the configuration will return the best default
	 * implementation. This will also set the return type to the interface type
	 * which reduces the need to cast the returned bean.
	 * 
	 * @param <T>
	 * @param clazz
	 *            interface class
	 * @return default context implementation
	 */
	public static <T> T getBean(Class<T> clazz) {
		return CONTEXT.getBean(clazz);
	}

	/**
	 * Generic way of getting a bean from the context.
	 * 
	 * @param name
	 *            bean name
	 * @return context implementation of the requested bean
	 */
	public static Object getBean(String name) {
		return CONTEXT.getBean(name);
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		logger.debug("setting application context");
		CONTEXT = context;
	}
}
